<template>
	<view class="content">
		<!-- 驶泰 -->
		<u-navbar :fixed="false" title="工单" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff"></u-navbar>

		<view class="MainBox">
			<u--form labelPosition="left" :model="formData" :rules="rules" ref="uForm">
				<u-form-item labelWidth="100" label="工单编号" borderBottom leftIcon="order"
					:leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.BillNO" placeholder="自动生成" readonly border="none"></u--input>
				</u-form-item>

				<u-form-item labelWidth="100" label="产品名称" prop="ProductName" borderBottom leftIcon="file-text" required
					@click="openBaseScreen('产品','radio')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.ProductName" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="工艺路线" prop="Routing" borderBottom leftIcon="share" required
					@click="openBaseScreen('工艺路线','other')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.Routing" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="工作中心" prop="FWorkshopName" borderBottom leftIcon="file-text"
					required @click="openBaseScreen('工作中心','radio')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.FWorkshopName" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="是否线性" prop="IsLinear" borderBottom leftIcon="file-text" required
					@click="openBaseScreen('线性','radio')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.IsLinear" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="计划数" prop="FPlanQty" leftIcon="coupon" required
					:leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.FPlanQty" type="number" placeholder="请输入" border="none"></u--input>
				</u-form-item>


				<!-- 起止时间 -->
				<u-form-item labelWidth="100" leftIcon="calendar" :leftIconStyle="{'font-size':'20px'}"
					style="margin-top: 10px;">
					<view class="ChoiceTimesBox">

						<view class="TimeBox">

							<view class="StartTime timer" @click="ChoiceTime('start')">
								<!-- <view class="TimeText"> -->
								<text>计划开始时间</text>
								<text>{{dateFormat(formData.StartTime) }}</text>
								<!-- </view> -->
							</view>

							<view class="Icon">
								<u-icon name="minus" size="30"></u-icon>
							</view>

							<view class="EndTime timer" @click="ChoiceTime('end')">
								<!-- <view class="TimeText"> -->
								<text>计划结束时间</text>
								<text>{{dateFormat(formData.EndTime)}}</text>
								<!-- </view> -->
							</view>
						</view>
					</view>
				</u-form-item>

				<u-form-item labelWidth="100" style="margin-top: 10px;" label="用料清单" leftIcon="file-text"
					:leftIconStyle="{'font-size':'20px'}" @click="openBaseScreen('用料清单','other')">
					<!-- <u--input v-model="formData.MaterialsListTotal" disabled disabledColor="#ffffff" placeholder="暂无用料"
							border="none"></u--input> -->
					<view v-if="formData.MaterialsListTotal" style="letter-spacing: 3px;">
						<text>共需</text>
						<text
							style="color: #51d0d0;font-weight: 600;margin: 0 4px;font-size: 16px;">{{formData.MaterialsListTotal}}</text>
						<text>种物料</text>
					</view>

					<view v-else>
						<text style="color: #999;">暂无用料</text>
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>


				<!-- <u-form-item label="附件" leftIcon="attach" :leftIconStyle="{'font-size':'20px'}" class="TopOption"
					style="margin-top: 10px;">
					<view class="" style="padding: 10px 20px 0;width: 100%;">
						<u-upload :fileList="formData.AnnexList" @afterRead="afterRead" @delete="deletePic" name="3"
							multiple :maxCount="1" :previewFullImage="true" delete-icon-size="40px"></u-upload>
					</view>
				</u-form-item> -->

				<u-form-item labelWidth="100" label="备注" prop="Remark" leftIcon="file-text"
					:leftIconStyle="{'font-size':'20px'}" class="TopOption" style="margin-top: 10px;">
					<view class="" style="padding: 10px 20px 0;width: 100%;">
						<u--textarea v-model="formData.Remark" placeholder="请输入内容" count maxlength="150"></u--textarea>
					</view>
				</u-form-item>

			</u--form>

			<!-- 时间选择器 -->
			<u-datetime-picker ref="datetimePicker" :title="PickerTitle" :show="showTimePicker" v-model="DatetimeData"
				mode="date" :closeOnClickOverlay="true" @close="ClosePicker" @cancel="ClosePicker"
				@confirm="ConfirmTime" :formatter="formatter"></u-datetime-picker>
		</view>

		<view class="BottomBox" :style="$utils.disposeSafeBottomFun()">
			<button :disabled="!enabledSubmitBtn" v-if="formData.WoOrderID == 0" class="content_bottom_primary_Btn"
				style="width: 90%;margin: 0 auto !important;" @click="saveRow('create')">创建</button>

			<view v-else-if="formData.WoOrderID != 0 && !formData.Approve" class="x-ec" style="width: 100%;">
				<button :disabled="!enabledSubmitBtn" v-if="ApproveBack('修改')"
					class="content_bottom_primary_Btn CommonBtnSize" style="margin-left: 10px !important;"
					@click="saveRow('edit')">修改</button>
				<button :disabled="!enabledSubmitBtn" v-if="ApproveBack('审核')"
					class="content_bottom_primary_plainBtn CommonBtnSize" style="margin-left: 10px !important;"
					@click="saveRow('Audit')">审核</button>
				<!-- @click="AuditBtn(1)">审核</button> -->
			</view>


			<view v-else-if="formData.WoOrderID != 0 && formData.Approve" class="x-ec" style="width: 100%;">
				<!-- <button
					style="background-color: #fff;color: #51d0d0;border: 1px solid #51d0d0;width: 20%;margin-left: 10px !important;min-width: 90px;"
					@click="saveRow('change')">生成变更单</button> -->
				<button :disabled="!enabledSubmitBtn" v-if="FCJType == 1 && ApproveBack('发放派工')"
					class="content_bottom_primary_Btn CommonBtnSize" style="margin-left: 10px !important;"
					@click="OpenDispatchBtn">发放派工</button>
				<button :disabled="!enabledSubmitBtn" v-if="ApproveBack('撤审')"
					class="content_bottom_primary_plainBtn CommonBtnSize" style="margin-left: 10px !important;"
					@click="AuditBtn">撤审</button>
			</view>



		</view>


		<u-popup class="MainPopup" :show="OpenDispatchPopup" mode="center" :round="12" zIndex="999999">
			<view class="PopupContent f-dc">
				<u-navbar :fixed="false" title="分发派工" :autoBack="false" leftIcon=" " :safeAreaInsetTop="false"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="CloseDispatch"></uni-icons>
					</view>
				</u-navbar>

				<view class="PopupMainBox">
					<view class="CellBox x-f">
						<view class="LeftBox">
							<text>发放类型:</text>
						</view>
						<uni-data-select style="flex: 1;" v-model="DispatchSelect" :localdata="DispatchRange"
							placeholder="请选择"></uni-data-select>
					</view>


					<view class="CellBox x-f" v-if="DispatchSelect && DispatchSelect != 3">
						<view class="LeftBox">
							<text>发放数量:</text>
						</view>
						<u--input type="digit" placeholder="请输入发放数量" border="surround"
							v-model="DispatchValue"></u--input>
					</view>

				</view>


				<view class="PopupBottomBox">
					<button class="CancelBtn" size="mini" @click="CloseDispatch">取消</button>
					<button class="ComfirmBtn" size="mini" @click="ComfirmDispatchBtn">确定</button>
				</view>
			</view>
		</u-popup>

		<m-loading :text="loadingText" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	/* 新建工单 */
	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;
	export default {
		data() {
			return {
				enabledSubmitBtn: false, // 控制按钮是否启用
				showMLoading: false, // 加载动画
				loadingText: "正在渲染",
				FCJType: 2, // 查询公司报工类型 1、派工 2、工单
				formData: {
					WoOrderID: 0,

					BillNO: '', // 产品编号
					ProductName: '', // 产品名称
					ProductCode: '',
					ProductID: '',

					Routing: '', // 工艺路线

					FWorkshopName: '', // 工作中心
					FWorkshopID: '', // 工作中心

					IsLinear: '', // 是否线性
					IsLinearID: '',

					FPlanQty: null, // 计划数
					AbnormalReport: '', // 异常报工
					MaterialsListTotal: '', // 用料清单
					AnnexList: [], // 附件
					FilePath: '', // 附件地址
					Remark: '', // 备注

					StartTime: new Date(), // 开始时间,
					EndTime: new Date(), // 结束时间
				},
				rules: {
					'ProductName': {
						type: 'string',
						required: true,
						message: '产品不能为空',
						trigger: ['change']
					},
					'Routing': {
						type: 'string',
						required: true,
						message: '工艺路线不能为空',
						trigger: ['change']
					},
					'FWorkshopName': {
						type: 'string',
						required: true,
						message: '工作中心不能为空',
						trigger: ['change']
					},
					'IsLinear': {
						type: 'string',
						required: true,
						message: '是否线性不能为空',
						trigger: ['change']
					},
					'FPlanQty': {
						type: 'number',
						required: true,
						message: '计划数不能为空',
						trigger: ['change']
					},
				},
				RoutingData: [], // 工艺路线数据数组
				MaterialsList: [], // 用料清单数组数据
				DatetimeData: Number(new Date()), // 时间选择器时间
				showTimePicker: false, // 时间选择器弹层显示
				TimeType: '', // 区分时间 start - 开始 ， end - 结束
				PickerTitle: '', // 时间弹层标题

				OpenDispatchPopup: false, // 发放派工弹层
				DispatchSelect: '', // 发放派工选中数据
				DispatchValue: null, // 发放数量
				DispatchRange: [{
						value: 3,
						text: "全部派工"
					},
					{
						value: 2,
						text: "按张数分发"
					},
					{
						value: 1,
						text: "按数量分发"
					},
				],
				OpenAddEventListen: false, // 是否在页面关闭时开启监听
				ListenName: '', // 开启监听的名称

				BtnApprove: [], // 权限数组
			}
		},
		onReady() {
			// 微信小程序需要用此写法
			// this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		onShow() {
			// console.log(this.Request.dateFormat(new Date(), 'Y-MM-dd'))
		},
		onLoad(option) {
			var that = this;
			// 当没有值传入
			// console.log(JSON.stringify(option));
			// console.log(this.$store.getters.GetFCJType)

			let foundNode = null;
			// 获取页面按钮权限
			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '生产管理') {
					for (const node of module.Node) {
						if (node.APFunName === '新建工单') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}

			this.BtnApprove = this.$utils.isEmpty(foundNode) ? [] : foundNode['IconApprove'];

			// 判断
			if (option.openListen) {
				that.OpenAddEventListen = true;
				that.ListenName = option.openListen;
			}

			// that.FCJType = this.$store.getters.GetFCJType; // 查询公司报工类型
			that.FCJType = this.$store.getters.GetFCJType; // 查询公司报工类型


			if (this.$utils.isEmpty(option)) {
				this.formData.WoOrderID = 0;
				this.enabledSubmitBtn = true;
			} else {
				// 当有值传入
				this.formData.WoOrderID = option.WoOrderID;
				setTimeout(() => {
					that.IsEdit();
				}, 300)
			}
		},
		created() {},
		watch: {
			FPlanQty: {
				handler(newVal) {
					var that = this;
					console.log(newVal)
					that.$refs.uForm.validateField('FPlanQty');
				},
				deep: true,
			},
		},
		mounted() {
			var that = this;
			// 监听 选择产品
			uni.$on('CreateTicet_Choice', function(ret) {
				console.log(ret)
				if (ret.type == '产品') {
					// that.formData.ProductName = ret.data.ProductName;
					// that.formData.ProductID = ret.data.Index;

					that.formData = Object.assign(that.formData, ret.data);

					setTimeout(() => {
						that.ProductToGetInfo(); // 根据产品获取工艺路线、用料清单 
					}, 50)

					that.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: {}
					})
				} else if (ret.type == '工艺路线') {

					// 记录数据
					let Data = JSON.parse(JSON.stringify(that.$store.state.TicketModule.CreateTicket_Routing));
					that.RoutingData = Data;

					// 将工艺路线名称数据提取出来 用 '、' 分割
					let GetRouting = Data.map(item => {
						return item.ProcedureName
					})
					that.formData.Routing = GetRouting.join('、');

					setTimeout(() => {
						that.$refs.uForm.validate();

						// 清除vuex 中工艺路线的数据
						let Obj = {
							Name1: 'CreateTicket_Routing',
							data: {}
						};

						that.$store.commit('TicketModule/ChangeAndSetStateData', Obj);
					}, 300)
				} else if (ret.type == '工作中心') {

					that.formData = Object.assign(that.formData, ret.data);

					that.$refs.uForm.validate();
					that.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: {}
					})
				} else if (ret.type == '用料清单') {
					let Data = JSON.parse(JSON.stringify(ret.data));
					that.MaterialsList = Data;
					that.formData.MaterialsListTotal = Data.length;
					// console.log(JSON.stringify(Data))

					// let Materials_BomID = Data.map(item => {
					// 	return item.BomID;
					// })
					// let Materials_BomDeID = Data.map(item => {
					// 	return item.BomDeID;
					// })

					// console.log(JSON.stringify(Materials_BomID.join('~')))
					// console.log(JSON.stringify(Materials_BomDeID.join('~')))

					that.$store.commit('TicketModule/ChangeAndSetStateData', {
						Name1: 'CreateTicket_Materials',
						data: []
					});
				} else if (ret.type == '线性') {

					that.formData = Object.assign(that.formData, ret.data);

					that.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: {}
					})
				}
			});


			// 组件中监听队列完成
			this.$onQueueEvent('queueEmpty', () => {
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				console.log('新建工单页面所有请求完成');

				that.$utils.hideLoading();
				that.enabledSubmitBtn = true; // 解开按钮限制
				that.showMLoading = false;
				setTimeout(() => {
					that.loadingText = "正在渲染";
				}, 500);
			});

		},
		onUnload() { // 监听页面卸载,
			// 关闭监听器
			// if (!this.$utils.isEmpty(this.ListenName)) {
			// 	uni.$off(this.ListenName)
			// }
			uni.$off('Refresh_List')
		},
		methods: {
			ApproveBack(str) {
				let that = this;
				let Type = that.BtnApprove.some(item => {
					return item.MenuName == str
				})

				return Type;
			},
			TriggerListen() {
				// if (!this.$utils.isEmpty(this.ListenName)) {
				// 	uni.$emit(this.ListenName)
				// }
				uni.$emit('Refresh_List');

			},
			IsEdit() { // 修改工单——查询工单信息
				var that = this;
				that.$request('XGD_SelectWoOrder', {
					WoOrderID: that.formData.WoOrderID
				}, function(ret) {
					if (ret.status == 200) {
						// 主表信息

						that.formData = that.formData = Object.assign(that.formData, ret.data.ds[0]);
						that.formData.IsLinear = ret.data.ds[0]['IsLinear'] == 1 ? '是' : '否';
						that.formData.IsLinearID = ret.data.ds[0]['IsLinear'];
						// 赋值工艺路线
						that.RoutingData = ret.data.ds1;
						// 拼接工艺路线数据
						let GetRouting = ret.data.ds1.map(item => {
							return item.ProcedureName
						})
						that.formData.Routing = GetRouting.join('、');



						that.MaterialsList = ret.data.ds2;
						that.formData.MaterialsListTotal = ret.data.ds2.length;

						// console.log(JSON.stringify(that.formData))

						// 触发监听
						that.TriggerListen();
						that.$refs.uForm.validate();
					} else {
						uni.showToast({
							title: '接口请求异常，请重试'
						})
					}
				})
			},
			ProductToGetInfo() { // 根据产品获取工艺路线、用料清单
				var that = this;

				that.$request('XGD_SelectBomAndProc2', {
					ProductID: that.formData.ProductID
				}, function(ret) {
					if (ret.status == 200) {

						// 赋值工艺路线
						that.RoutingData = ret.data.ds;
						// 拼接工艺路线数据
						let GetRouting = ret.data.ds.map(item => {
							return item.ProcedureName
						})
						that.formData.Routing = GetRouting.join('、');
						if (ret.data.ds.length && ret.data.ds[0]?.IsLinear !== undefined) {
							that.formData.IsLinear = ret.data.ds[0]['IsLinear'] == 1 ? '是' : '否';
							that.formData.IsLinearID = ret.data.ds[0]['IsLinear'];
						} else {
							that.formData.IsLinear = '否';
							that.formData.IsLinearID = 0;
						}


						// 用料清单
						that.MaterialsList = ret.data.ds1;
						that.formData.MaterialsListTotal = ret.data.ds1.length;
						that.$refs.uForm.validate();
					}
				})
			},
			dateFormat(val) { // 格式化时间
				var that = this;
				if (!that.$utils.isEmpty(val)) {
					return that.Request.dateFormat(new Date(val), 'Y-MM-dd');
				} else {
					return that.Request.dateFormat(new Date(), 'Y-MM-dd');
				}
			},
			formatter(type, value) { // 时间选择器数据格式化
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			ChoiceTime(type) { // 点击计划时间
				var that = this;
				this.TimeType = type;
				if (type == 'start') {
					that.DatetimeData = Number(that.formData.StartTime);
					this.PickerTitle = '计划开始时间';
				} else if (type == 'end') {
					that.DatetimeData = Number(that.formData.EndTime);
					this.PickerTitle = '计划结束时间';
				} else {
					that.DatetimeData = Number(new Date());
					this.PickerTitle = '';
				}

				that.showTimePicker = true;
			},
			ClosePicker() { // 关闭时间选择器
				this.DatetimeData = Number(new Date());
				this.showTimePicker = false;
			},
			ConfirmTime(data) { // 确认时间
				// console.log(data.value)

				if (this.TimeType == 'start') {
					this.formData.StartTime = data.value;
				} else if (this.TimeType == 'end') {
					this.formData.EndTime = data.value;
				}
				this.showTimePicker = false;
			},
			openBaseScreen(str, type) { // 前往筛选页
				let that = this;

				if (type == 'radio') {
					let obj = null;
					let url = '/commonPage/Tool/baseScreen';
					// console.log(str)
					if (str == '产品') {

						obj = {
							allowClear: false,
							cmd: 'XGD_Product2',
							type: str,
							ListeningName: 'CreateTicet_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'ProductInfo', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								subText: [{
									label: '描述',
									labelKey: 'desc'
								}],
								ChoiceDataKey: 'ProductID',
								ChoiceDataData: this.formData.ProductID,
							},
							param: {
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '工作中心') {

						obj = {
							allowClear: false,
							cmd: 'XGD_Workshop',
							type: str,
							ListeningName: 'CreateTicet_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'FWorkshopName', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								// subText: [{
								// 	label: '描述',
								// 	labelKey: 'desc'
								// }],
								ChoiceDataKey: 'FWorkshopID',
								ChoiceDataData: this.formData.FWorkshopID,
							},
							param: {
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '线性') {

						obj = {
							allowClear: false,
							cmd: '',
							type: str,
							ListeningName: 'CreateTicet_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: false, //是否分页
								// searchKey: '', //搜索关键词，应包含在param中
								showText: 'IsLinear', //查询结果显示的字段
								// pageIndexStr: 'pageIndex', //分页页码字段，应包含在param中
								// subText: [{
								// 	label: '描述',
								// 	labelKey: 'desc'
								// }],
								ChoiceDataKey: 'IsLinearID',
								ChoiceDataData: this.formData.IsLinearID,
							},
							param: {
								data: [{
									IsLinear: '是',
									IsLinearID: 1
								}, {
									IsLinear: '否',
									IsLinearID: 0
								}]
							}
						};

						url = '/commonPage/Tool/baseScreen?select=1';
					}

					// 
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})

					uni.navigateTo({
						url: url
					})
				} else if (type == 'other') {
					if (str == '工艺路线') {

						// 将当前工艺路线数据存储到vuex中，方便获取
						let Obj = {
							Name1: 'CreateTicket_Routing',
							data: {
								RoutingData: this.RoutingData,
								FWorkshop: {
									FWorkshopName: this.formData.FWorkshopName,
									FWorkshopID: this.formData.FWorkshopID,
								},
								FormData: this.formData
							}
						};

						this.$store.commit('TicketModule/ChangeAndSetStateData', Obj);

						uni.navigateTo({
							url: './ChoiceRouting'
						})
					} else if (str == '用料清单') {
						// console.log(JSON.stringify(this.MaterialsList))

						let Obj = {
							Name1: 'CreateTicket_Materials',
							data: this.MaterialsList
						};

						this.$store.commit('TicketModule/ChangeAndSetStateData', Obj);

						uni.navigateTo({
							url: './MaterialsList?ProductID=' + this.formData.ProductID
						})

					}
				}
			},
			// 删除图片
			deletePic(event) {
				// console.log(JSON.stringify(event))
				this.formData.AnnexList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData.AnnexList.length
				lists.map((item) => {
					this.formData.AnnexList.push({
						...item,
						type: 'add',
						status: 'uploading',
						message: '上传中'
					})
				})

				// console.log(JSON.stringify(this.formData.AnnexList))
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.formData.AnnexList[fileListLen]
					this.formData.AnnexList.splice(fileListLen, 1, Object.assign(item, {
						status: '', // 当值为 success 时，会显示 成功图标
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return url
				// return new Promise((resolve, reject) => {
				// 	let a = uni.uploadFile({
				// 		url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
				// 		filePath: url,
				// 		name: 'file',
				// 		formData: {
				// 			user: 'test'
				// 		},
				// 		success: (res) => {
				// 			setTimeout(() => {
				// 				resolve(res.data.data)
				// 			}, 1000)
				// 		}
				// 	});
				// })
			},
			saveRow(str) { // 创建按钮
				var that = this;
				if (!this.enabledSubmitBtn) {
					return;
				}

				this.showMLoading = true;
				this.loadingText = "正在验证字段";
				this.enabledSubmitBtn = false;

				this.$refs.uForm.validate().then(res => {
					that.loadingText = "验证成功，准备提交";
					// uni.$u.toast('校验通过');

					// that.$utils.showLoading();

					let ProcessRouteIDs = [],
						ProcessRouteDeIDs = [],
						ProcedureIDs = [],
						WoFWorkshopIDs = [],
						EquipmentTypeIDs = [],
						MoludTypeIDs = [],
						LabourCost = [],
						ManHour = [],
						HourGJ = [],
						Outsource = [],

						BomIDs = [],
						BomDeIDs = [],
						WoPartIDs = [],
						WoPROCIDs = [],
						ProductSunIDs = [],
						ParentNums = [],
						SunNumes = [],
						LossRatios = [];

					// console.log(JSON.stringify(that.RoutingData))
					that.RoutingData.forEach(item => {
						ProcessRouteIDs.push(item.ProcessRouteID || 0);
						ProcessRouteDeIDs.push(item.ProcessRouteDeID || 0);
						ProcedureIDs.push(item.ProcedureID || 0);
						WoFWorkshopIDs.push(item.FWorkshopID || that.formData.FWorkshopID);
						EquipmentTypeIDs.push(item.EquipmentTypeID || 0);
						MoludTypeIDs.push(item.MoludTypeID || 0);
						LabourCost.push(item.LabourCost || 0);
						ManHour.push(item.ManHour || 0);
						HourGJ.push(item.HourGJ || 0);
						Outsource.push(Number(item.Outsource) || 0);
						WoPROCIDs.push(item.WoPROCID || 0);
					});

					that.MaterialsList.forEach(item => {
						BomIDs.push(item.BomID || 0);
						BomDeIDs.push(item.BomDeID || 0);
						WoPartIDs.push(item.WoPartID || 0);
						ProductSunIDs.push(item.ProductID || 0);
						ParentNums.push(item.ParentNum || 0);
						SunNumes.push(item.SunNume || 0);
						LossRatios.push(item.LossRatio || 0);

					})

					let obj = {
						WoOrderID: !that.$utils.isEmpty(that.formData.WoOrderID) ? that.formData.WoOrderID :
						0, // 工单ID
						ProductID: that.formData.ProductID, // 产品ID

						ProcessRouteID: ProcessRouteIDs.join('~'), // 工艺路线主表ID
						ProcessRouteDeID: ProcessRouteDeIDs.join('~'), // 工艺路线子表ID
						ProcedureID: ProcedureIDs.join('~'), // 工序ID

						WoFWorkshopID: WoFWorkshopIDs.join('~'), // 工序生产车间
						EquipmentTypeID: EquipmentTypeIDs.join('~'), // 设备类型
						MoludTypeID: MoludTypeIDs.join('~'), // 模具类型
						LabourCost: LabourCost.join('~'), // 计件单价
						ManHour: ManHour.join('~'), // 工时
						HourGJ: HourGJ.join('~'), // 工时工价
						Outsource: Outsource.join('~'), // 是否外协

						FWorkshopID: that.formData.FWorkshopID, // 工作中心
						IsLinear: that.formData.IsLinearID, // 是否线性
						FPlanQty: that.formData.FPlanQty, // 计划数量
						DueStartDate: that.dateFormat(that.formData.StartTime), // 开始时间
						DueEndDate: that.dateFormat(that.formData.EndTime), // 结束时间


						BomID: BomIDs.join('~'), // Bom主表ID
						BomDeID: BomDeIDs.join('~'), // Bom子表ID
						ProductSunID: ProductSunIDs.join('~'), // 配件ID
						ParentNum: ParentNums.join('~'), // 父件基数
						SunNume: SunNumes.join('~'), // 子件用量
						LossRatio: LossRatios.join('~'), // 损耗率%

						FilePath: that.formData.FilePath, // 文件地址
						Comment: that.formData.Remark, // 备注
						WoPROCID: WoPROCIDs.join('~'), // gylx

						WoPartID: WoPartIDs.join('~'), // bom

					};

					if (str == 'create' || str == 'edit' || str == 'Audit') {
						try {
							that.loadingText = "正在提交";
							console.log(obj);
							that.$request('XGD_SubmitAndUpdate', obj, function(ret) {

								if (ret.status == 200) {
									if (ret.data.ds[0].Status == 200) {

										if (str == 'Audit') { // 审核
											that.AuditBtn();

										} else {

											that.formData.WoOrderID = ret.data.ds[0].WoOrderID;
											// 调用修改查询接口，赋值数据
											that.IsEdit();
											that.$utils.hideLoading();
											setTimeout(() => {
												// uni.$u.toast(ret.data.ds[0].msg);
												/* uni.showToast({
													title: ret.data.ds[0].msg
												}) */
												that.loadingText = "提交成功";
											}, 300);
										}

									} else {
										that.$utils.hideLoading();
										uni.showToast({
											title: ret.data.ds[0].msg,
											icon: 'none'
										})
									}
								} else {
									that.$utils.hideLoading();
								}
							}, function(err) {
								if (err.data.status == 500) {
									that.$utils.hideLoading();

									uni.showToast({
										title: err.data.msg,
										icon: 'none'
									})
								} else if (err.status == 500) {

									that.$utils.hideLoading();
									uni.showToast({
										title: err.msg,
										icon: 'none'
									})
								}
							})
						} catch (e) {
							//TODO handle the exception

							that.$utils.hideLoading();
							uni.showToast({
								title: '提交异常，请重试',
								icon: 'none'
							})
						}

					} else if (str == 'change') {
						// 调用变更单
						try {
							// that.$request('XGD_SubmitAndUpdate', obj, function(ret) {

							// })

						} catch (e) {
							//TODO handle the exception
						}

					}


				}).catch(errors => {
					console.log(JSON.stringify(errors))
					that.showMLoading = false;
					this.enabledSubmitBtn = true;
					if (Array.isArray(errors)) {

						that.$utils.hideLoading();
						uni.$u.toast('请完善表单')
					}
				});

			},
			AuditBtn() { // 审核按钮
				var that = this;
				let type = that.formData.Approve ? '-1' : '1';

				// that.$utils.showLoading();
				this.showMLoading = true;

				that.loadingText = that.formData.Approve ? '正在撤审' : '正在审核';
				that.$request('XGD_ApproveAndSend', {
					FType: '审核',
					approveFType: type,
					WoOrderID: that.formData.WoOrderID,
					approvalType: 0,
					LZMNum: 0,
				}, function(ret) {
					// console.log(JSON.stringify(ret))

					if (ret.status == 200) {
						if (ret.data.ds[0].RZT == 500) {
							that.$utils.hideLoading();

							layer.alert(ret.data.ds[0].RMS)

							/* uni.showToast({
								title: ret.data.ds[0].RMS,
								icon: 'none'
							}) */
							return
						} else {
							that.IsEdit();

							that.$utils.hideLoading();
							let msg = '成功';
							if (type == 1) { // 审核
								msg = '审核成功';

								if (that.FCJType == 2) {
									that.IsEdit();

									that.$utils.hideLoading();

								}

							} else if (type == -1) { // 反审核
								msg = '已撤审';
							}
							/* uni.showToast({
								title: msg,
								icon: 'none'
							}) */

							that.loadingText = msg;
						}
					} else {
						that.$utils.hideLoading();

					}
				}, function(err) {
					if (err.data.status == 500) {
						that.$utils.hideLoading();

						uni.showToast({
							title: err.data.msg,
							icon: 'none'
						})
					} else if (err.status == 500) {
						that.$utils.hideLoading();

						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
				})

			},
			OpenDispatchBtn() { // 打开发放派工弹层
				var that = this;
				// that.OpenDispatchPopup = true;

				// console.log(that.formData)
				let data = {
					form: this.formData,
					ProgressList: this.RoutingData,
				};

				let obj = {
					Name1: 'CreateTicket_Routing',
					data: data
				}

				this.$store.commit('TicketModule/ChangeAndSetStateData', obj);

				uni.navigateTo({
					url: './DispatchList/CreateDispatch'
				})
			},
			CloseDispatch() { // 关闭发放派工弹层
				var that = this;
				that.OpenDispatchPopup = false;

				that.$utils.hideLoading();

				that.DispatchSelect = '';
				that.DispatchValue = '';

			},
			ComfirmDispatchBtn() { // 发放派工
				var that = this;
				if (!this.enabledSubmitBtn) {
					return;
				}

				this.enabledSubmitBtn = false;

				if (that.$utils.isEmpty(that.DispatchSelect)) {
					return uni.showToast({
						title: '请选择发放类型',
						icon: 'none'
					});
				}

				if (that.DispatchSelect != 3 && that.$utils.isEmpty(that.DispatchValue)) {
					that.DispatchValue = '';
					return uni.showToast({
						title: '请填写发放数量',
						icon: 'none'
					});
				}

				if (that.DispatchSelect != 3 && that.DispatchValue.indexOf('.') != -1) {
					return uni.showToast({
						title: '发放数量必须是整数',
						icon: 'none'
					});
				}

				this.showMLoading = true;
				this.loadingText = "正在准备发放";

				try {

					// that.$utils.showLoading();

					that.$request('XGD_ApproveAndSend', {
						FType: '发放',
						approvalType: that.DispatchSelect,
						WoOrderID: that.formData.WoOrderID,
						LZMNum: that.DispatchValue || 0,
						approveFType: 0,
					}, function(ret) {
						console.log(JSON.stringify(ret))

						if (ret.status == 200) {

							if (ret.data.ds[0].RZT == 500) {
								/* uni.showToast({
									title: ret.data.ds[0].RMS,
									icon: 'none'
								}) */
								layer.alert(ret.data.ds[0].RMS)
								that.showMLoading = false;
								setTimeout(() => {
									that.CloseDispatch();
								}, 500)
								return
							} else {

								that.IsEdit();

								that.$utils.hideLoading();
								/* uni.showToast({
									title: '发放成功',
									icon: 'none'
								}) */

								that.loadingText = "发放成功";
								setTimeout(() => {
									that.CloseDispatch();
								}, 500)
							}
						} else {

							that.$utils.hideLoading();
						}
					}, function(err) {
						if (err.data.status == 500) {

							that.$utils.hideLoading();
							/* uni.showToast({
								title: err.data.msg,
								icon: 'none'
							}) */
							layer.alert(err.data.msg)
						} else if (err.status == 500) {
							that.$utils.hideLoading();
							layer.alert(err.msg)

							/* uni.showToast({
								title: err.msg,
								icon: 'none'
							}) */
						}
					})

				} catch (e) {

					that.$utils.hideLoading();
					//TODO handle the exception
				}

			},
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		// height: calc(100vh - 60px);
		background-color: #f9f9f9;

		uni-button {
			margin-left: initial !important;
			margin-right: initial !important;
		}

		.MainPopup {
			flex: initial !important;

			.PopupContent {
				display: flex;
				flex-direction: column;
				min-height: 240px;
				width: 90vw;
			}

			.u-transition {
				z-index: 99999 !important;
			}


			.PopupMainBox {
				padding: 12px 10px 6px;
				flex: 1;
				// overflow: auto;

				.CellBox {
					margin-bottom: 20px;

					.LeftBox {
						font-size: 14px;
						color: #999;
						margin-right: 10px;
					}
				}

				.uni-input-placeholder {
					color: #6a6a6a !important;
					font-size: 12px !important;
				}
			}

			.PopupBottomBox {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 10px 10px;

				.CancelBtn {
					background-color: #fff;
					color: #51d0d0;
					border: 1px solid #51d0d0;
					min-width: 80px;
				}

				.ComfirmBtn {
					background-color: #51d0d0;
					color: #fff;
					min-width: 80px;
					margin-left: 10px !important;
				}
			}
		}

		.MainBox {
			flex: 1;
			overflow: auto;
			// padding: 10px;

			// 表单1
			.u-form {
				// padding: 0px 10px;

				.u-form-item {
					background-color: #fff;
					padding: 0 16px;
				}


				.TopOption {

					.u-form-item__body {
						flex-direction: column !important;
					}
				}

				// 起止时间
				.ChoiceTimesBox {
					width: 100%;
					display: flex;
					align-items: center;
					// background-color: #fff;
					// padding: 18px 10px;
					// margin-top: 10px;

					.TimeBox {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-evenly;

						.timer {
							width: 100%;
							flex: 2;
							display: flex;
							flex-direction: column;
							// align-items: center;
							font-size: 14px;
							color: #333;

							text:first-child {
								margin-bottom: 10px;
								font-weight: 600;
							}

							text:last-child {
								height: 20px;
							}
						}

						.Icon {
							flex: 1;
						}
					}
				}


				// 上传-删除图标
				.u-upload__deletable {
					width: 20px;
					height: 20px;

					.u-upload__deletable__icon {
						right: -1px !important;

						.u-icon__icon {
							font-size: 20px !important;
							line-height: 16px !important;
						}
					}
				}
			}
		}

		.BottomBox {
			width: 100%;
			// height: 70px;
			// line-height: 70px;
			padding: 6px 15px;
			border-top: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;
			// padding-bottom: constant(safe-area-inset-bottom) !important;
			// padding-bottom: env(safe-area-inset-bottom) !important;
		}
	}
</style>